//
//  ZYMainTopView.m
//  YaYa
//
//  Created by 张亚 on 2019/1/9.
//  Copyright © 2019年 张亚. All rights reserved.
//

#import "ZYMainTopView.h"

@interface ZYMainTopView ()

@property (nonatomic, strong) UIView *lineView;

@property (nonatomic, strong) NSMutableArray * buttons;

@end

@implementation ZYMainTopView
- (NSMutableArray *)buttons {
    if (_buttons == nil) {
        _buttons = [NSMutableArray array];
    }
    return _buttons;
}

- (instancetype)initWithFrame:(CGRect)frame titleNames:(NSArray *)titles {
    self = [super initWithFrame:frame];
    if (self) {
        
        CGFloat btnW = self.frame.size.width / titles.count;
        CGFloat btnH = self.frame.size.height;
        
        for (int i = 0; i < titles.count; i++) {
            UIButton * titleBtn = [UIButton buttonWithType:UIButtonTypeCustom];
            
            [self.buttons addObject:titleBtn];
            
            NSString * vcName = titles[i];
            
            [titleBtn setTitle:vcName forState:UIControlStateNormal];
            [titleBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
            titleBtn.titleLabel.font = [UIFont systemFontOfSize:18];
            titleBtn.tag = i;
            titleBtn.frame = CGRectMake(i * btnW, 0, btnW, btnH);
            
            [titleBtn addTarget:self action:@selector(titleBtnDidClick:) forControlEvents:UIControlEventTouchUpInside];
            [self addSubview:titleBtn];
            
            if (i == 0) {
                
                CGFloat h = 2;
                CGFloat y = 40;
                [titleBtn.titleLabel sizeToFit];
                
                self.lineView = [[UIView alloc] init];
                self.lineView.backgroundColor = [UIColor whiteColor];
                self.lineView.height = h;
                self.lineView.width = titleBtn.titleLabel.width;
                self.lineView.y = y;
                self.lineView.centerX = titleBtn.centerX;
                
                [self addSubview:self.lineView];
            }
            
            
        }
        
    }
    return self;
}

- (void)scrolling:(NSInteger)tag {
    UIButton * button = self.buttons[tag];
    [UIView animateWithDuration:0.15 animations:^{
        self.lineView.centerX = button.centerX;
    }];
}

- (void)titleBtnDidClick:(UIButton *)button {
    if (self.topBlock) {
        self.topBlock(button.tag);
    }
    [self scrolling:button.tag];

}

@end
